<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          type="text"
          size="large"
          @click="handleSeniorLinked">
          高级关联
        </el-button>
        <el-button
          type="text"
          size="large"
          @click="handleSkuLinked">
          关联商品
        </el-button>
        <el-button
          type="text"
          size="large"
          :loading="btnLoading.export"
          :disabled="tableInfo.list.length === 0"
          @click="handleExportData">
          模板导出
        </el-button>
        <a>
          <Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}${apiObj.importExcel.url}`">
            <el-button type="text" size="large">
              模板导入
            </el-button>
          </Upload>
        </a>
        <el-button
          v-if="pageType === 2"
          type="text"
          size="large"
          @click="$router.push({ name: 'chageFromManageList' })">
          返回
        </el-button>
        <el-button
          type="text"
          size="large"
          :disabled="tableInfo.list.length === 0"
          :loading="btnLoading.submit"
          @click="handleSubmitData">
          提交
        </el-button>
      </el-row>
    </div>
    <el-form
      ref="formData"
      label-width="120px"
      class="input--reason--wrap"
      :model="formData">
      <el-form-item prop="launchReasonType" label="发起原因：">
        <el-select v-model="formData.launchReasonType" clearable>
          <el-option
            v-for="option in formData.launchReasonTypeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="launchReasonDesc" label="发起原因说明：">
        <el-input
          type="textarea"
          resize="none"
          v-model.trim="formData.launchReasonDesc"
          placeholder="请输入发起原因说明"
          :autosize="{ minRows: 3, maxRows: 4 }"
          :maxlength="100"
          show-word-limit/>
      </el-form-item>
    </el-form>
    <el-row class="page_wrap">
      <SkusTable
        showSelectCol
        :defaultMinWidth="120"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :selectionChange="handleSelectionChange"
        @handleCancelSelect="handleRemoveRow"/>
    </el-row>
    <FooterFields :footerFields="footerFields"/>
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      :submitLimitLength="3000"
      @seniorSearchResult="getSeniorResultFn"/>
    <!-- 关联商品弹框 -->
    <SkuLinkedDialog
      :visible.sync="skuLinked.visible"
      @getSelectRows="getSelectSkuRowsFn"/>
  </el-card>
</template>
<script>
import { tableColumns, LAUNCH_REASON_OPTIONS } from './constants';
import SkuLinkedDialog from './components/SkuLinkedDialog';
import { getBtnsId } from '@/libs/btnsPermission';
import SkusTable from '@/components/skusTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import {
  commitService,
  getRecordInfoService,
  getSkuSpecListService,
  exportExcelService,
} from '@/api/commodity/commodityManage/chageFromManage/skuSpecEdit';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { createExcelByExport, isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {
    SkusTable,
    SkuLinkedDialog,
    SeniorLinkedDialog,
    FooterFields,
  },
  data () {
    return {
      formData: {
        // 发起原因类型
        launchReasonType: '',
        // 发起原因说明
        launchReasonDesc: '',
        // 发起原因选择框
        launchReasonTypeOptions: LAUNCH_REASON_OPTIONS
      },
      tableInfo: {
        // 表格数据
        list: [],
        // 表格columns
        columns: tableColumns,
        // 勾选列表
        selection: [],
        // 表格加载loading
        loading: false
      },
      footerFields: {},
      recordNo: '',
      btnLoading: {
        submit: false,
        export: false,
      },
      // 1：修改页面 2：审核驳回重新修改页面
      pageType: '1',
      skuLinked: {
        visible: false
      },
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }]
      },
      apiObj: {
        // 导入模板
        importExcel: {
          url: 'sysback/modifySkuSaleAttr/importExcel'
        },
      },
    }
  },
  computed: {
    pageTitle () {
      let title = '修改SKU规格';
      // 1：修改页面
      if (this.pageType === 1) {
        return title;
      }
      // 2：审核驳回重新修改页面
      if (this.pageType === 2) {
        title = `${title}-表单修改页面`;
        return title;
      }
      return title;
    }
  },
  mounted () {
    const { recordNo } = this.$route.query;
    if (recordNo) {
      this.recordNo = recordNo;
      this.pageType = 2;
      this.getTableDataByRecordNo(recordNo);
    }
  },
  methods: {
    // 获取表单数据
    async getTableDataByRecordNo (recordNo) {
      const retData = await getRecordInfoService({ recordNo }, 'page_wrap');
      if (retData) {
        this.tableInfo.list = retData.skuSpecVoList;
        this.formData.launchReasonType = retData.launchReasonType;
        this.formData.launchReasonDesc = retData.launchReasonDesc;
        this.footerFields = retData;
      }
    },
    // 获取表单数据
    async getTableDataBySkuNos (skuNos) {
      if (skuNos.length === 0) {
        return false;
      }
      const data = { skuNos };
      const retData = await getSkuSpecListService(
        data,
        state => {
          this.tableInfo.loading = state;
        }
      );
      if (retData) {
        // 过滤掉已经存在的SKU
        this.tableInfo.list = this.tableInfo.list.filter(item => !skuNos.includes(item.skuNo));
        // 加入新关联的商品
        this.tableInfo.list.push(...retData);
      }
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 删除
    handleRemoveRow ({ index }) {
      const { skuNo } = this.tableInfo.list[index];
      this.tableInfo.list = this.tableInfo.list.filter(item => item.skuNo !== skuNo);
    },
    // 关联商品
    handleSkuLinked () {
      this.skuLinked.visible = true;
    },
    // 高级关联
    handleSeniorLinked () {
      const curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorLinked.visible = true;
    },
    // 获取批量关联的商品数据
    getSelectSkuRowsFn (data) {
      const skuNos = data.map(row => row.skuNo);
      this.getTableDataBySkuNos([...new Set(skuNos)]);
    },
    // 获取高级关联结果
    getSeniorResultFn (skuNos) {
      this.getTableDataBySkuNos([...new Set(skuNos)]);
    },
    // 导出
    async handleExportData () {
      const res = await exportExcelService(
        this.tableInfo.list,
        state => {
          this.btnLoading.export = state;
        }
      );
      createExcelByExport({ res, excelTitle: `修改SKU规格导出` });
    },
    // 上传格式验证失败
    handleUploadFormatError (file, fileList) {
      this.$message.error('格式错误');
    },
    // 上传之前
    handleBeforeUpload () {
      this.tableInfo.loading = true;
    },
    // 上传成功
    handleUploadSuccess (res) {
      this.tableInfo.loading = false;
      const { retData, retStatus, retMessage } = res;
      if (isResponseSuccessState(retStatus)) {
        // 每次导入成功后就重新加载表格columns，防止异常原因列污染
        this.tableInfo.columns = [].concat(tableColumns);
        this.$message.success('导入成功');
        this.tableInfo.list = retData;
      } else {
        this.$message.error(retMessage || '导入失败');
      }
    },
    // 上传失败
    handleUploadError () {
      this.tableInfo.loading = false;
      this.$message.error('上传失败');
    },
    // 提交
    async handleSubmitData () {
      if (this.tableInfo.list.length === 0) {
        this.$message.warning('请关联商品');
        return false;
      }
      if (!this.formData.launchReasonType) {
        this.$message.warning('请选择发起原因');
        return false;
      }
      if (this.formData.launchReasonType === '4' && !this.formData.launchReasonDesc) {
        this.$message.warning('请填写发起原因说明');
        return false;
      }
      const data = {
        updateParamList: this.tableInfo.list,
        recordNo: this.recordNo,
        launchReasonType: this.formData.launchReasonType,
        launchReasonDesc: this.formData.launchReasonDesc,
      };
      const retStatus = await commitService(
        data,
        state => {
          this.btnLoading.submit = state
        }
      );
      if (retStatus) {
        this.$message.success('提交成功');
        this.$router.push({ name: 'chageFromManageList' });
      }
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
